<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\business\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'app_id' => '2021001155682397',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmQrUzE+dANPCKu1Jvr8O9j7+X0AfPd5p9flxEx6rQEVF7vZDuyf7jyXOdMRP7+bxbhyhMabgpj+nuMBvHiGl7NEYO0ugtZtyo0eAy2UoMqPYw3gLvNxgKspOLj6WDZa0Qw0ExFX235+VZSfRwY+ZDEsRCXAh2lcs5W66O3Y6yF72CdscTfKBGLkhP6hIj9rGXNBT9olu1UmfLOuntiz+3Y6dbODZqLzmzVKy+MbRIt2ZNyje+n+wrCemwDucbkvadoq0/4JCnwe8CeY7SFb630nvoTe2kN9kuH6W/jiz7dEf6N75hMfiHZ5ff4bjpOYPvMEFbKwp23N50Db4Kvhz1wIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiFw3RgDzy6qWOGlF6k0gjzYwUY6y6ohWN1L8YvkgW0ARnzJdx2/2ekVLkAcFtD6LWUfEalPaETWtPl3k/z8EBMe2qGqETTg47FLcfIbZNoG/uFvidgoKWPBVzYCcND4sAApxJZolRrBRCJed5IOtwZ/Av2qmgqBzUuXEdkjOMaACbQKNoICe8hbbQJbpnv4qrxNQgVQpeAMvbchVcfVrNDx9xyjAHJ09pPS6bjI3qq7GyNhN2dSdBRIYyCQ+XCfDyFlLcjbxbPSUK5Sbtd8bbibCtfFcnfI2c9Qn6Y5f2ghidvJE4xQW+pkZObgbGXVBYEdLZfhu5Ygr4Ay2AK8xCQIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAiFw3RgDzy6qWOGlF6k0gjzYwUY6y6ohWN1L8YvkgW0ARnzJdx2/2ekVLkAcFtD6LWUfEalPaETWtPl3k/z8EBMe2qGqETTg47FLcfIbZNoG/uFvidg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1EjU2B0wCir33pGGmAGf7GyYHPAoY0zjsMibgECgYB4s0V1hIqL7cb8WAJQs6KXGsF01sofXdT5U8R6LTzDCCFjw2wLFs+TK515Zjw+dEF9QolJAbNqiTWJxznE4FZ3E4kn/oXXlo/i9FSdbqCYS5bpID/jF+0w9PnqxUB/qE77gxAR4uPv6m6fbE4HE9SXZHacBu0D50bvU9gsT2JYEQKBgF081p14fVnXOsNmeXvVBvOMj+Eyi/cAYRaq56m9NOvXrf4xY/nDC5m97tCLu+92tCznCeQ2sZuEUeNuQr01Qvu/c4ScbjemyOQc17z9iXTc3n6brOeYzlS1RC4rYEBofA6xtO3nSVLI4OPWodly4UFcKgEKQFmMhjtnb7GTq1sx'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {

    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
//    public function getParam()
    {
//        $no='201988887777412';$money=1; $body='test'; $subject = '1';
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = $this->config['app_id'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://www.yunping168.com/business/Ali/huidiaoali");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiaoali()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $result = $this->alltypespay($num);
                if($result == true){
                    return 'success';
                }else{
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}